#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/8/9 1:14
# @Author : LZQ
# @Version：V 0.1
# @File : goods.py
# @desc :
from . import api, good
from app.token_verify import verify
from flask import request, current_app, g, jsonify
from flask_sqlalchemy import Pagination
from sqlalchemy import and_, or_, desc
from app.models import Category, Attribute, Goods, GoodsAttr, GoodsCats, GoodsPics
from app.utils.image_storage import upload_qiniu, get_image_url
from __init__ import redis_store, db
import json
import os
from app.utils.fastdfs_utils import FDFS
import datetime, time
from PIL import Image
import decimal


@good.route("/exist", methods=['POST'])
@verify
def goods_name_is_exist():
    data = json.loads(request.get_data()) if request.get_data() else {}
    name = data.get("name")
    res = {"code": 200, "msg": "可以使用"}
    try:
        goods=Goods.query.filter_by(Goods.goods_name==name)
        if goods:
            res = {"code":400,"msg":"名字重复换一个试试"}
    except Exception as e:
        current_app.logger.error(e)
        res = {"code": 400, "msg": "名字重复换一个试试"}

    return jsonify()

@good.route("/list", methods=['GET'])
@verify
def get_goods():
    data = request.args if request.args else {}
    goods_list = []
    pagesize = int(data.get("pagesize")) if data.get("pagesize") else 5
    pagenum = int(data.get("pagenum")) if data.get("pagenum") else 1
    key = data.get("key")
    query = data.get('query')
    goods_filter = None
    if key == 'goods_name' and query:
        goods_filter = and_(Goods.goods_name.like('%{}%'.format(query)), Goods.is_del == '0')
    elif key == 'goods_price' and query:
        query = query if query in '-' else '0-50'
        price_start = query.split('-')[0]
        price_end = query.split('-')[1]
        goods_filter = and_(Goods.goods_price.between(price_start, price_end), Goods.is_del == '0')
    goods = Goods.query.filter(goods_filter).order_by(Goods.goods_price).paginate(pagenum,
                                                                                  pagesize) if key and query else Goods.query.filter(
        Goods.is_del == '0').order_by(
        Goods.goods_price if key == 'goods_price' else Goods.goods_name).paginate(pagenum, pagesize)
    for good in goods.items:
        goods_list.append(good.to_dict())
    data_dict = {"data": goods_list, "meta": {"code": 200, "msg": "获取商品列表成功", "total": goods.total}}
    return jsonify(data_dict)


@good.route("/del", methods=['POST'])
@verify
def del_goods():
    data = json.loads(request.get_data()) if request.get_data() else {}
    goods_id = data.get("goods_id")
    count = 0
    try:
        count = Goods.query.filter(Goods.goods_id == goods_id).update({"is_del": '1'})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
    if count != 0:
        data_dict = {"meta": {"code": 200, "msg": "删除成功"}}
    else:
        data_dict = {"meta": {"code": 400, "msg": "删除失败"}}
    return jsonify(data_dict)


@good.route('/edit', methods=['POST'])
@verify
def edit_goods():
    data = json.loads(request.get_data()) if request.get_data() else {}
    goods_name = data.get("goods_name")
    goods_id = data.get("goods_id")
    goods_price = data.get("goods_price")
    goods_weight = data.get("goods_weight")
    upd_time = int(time.time())
    if not all([goods_price, goods_weight, goods_id, goods_name]):
        return jsonify({"code": 505, "msg": "参数不全"})
    count = 0
    goods = None
    data_dict = {}
    try:
        goods_base = Goods.query.filter(Goods.goods_id == goods_id)
        count = goods_base.update(
            {"goods_name": goods_name, "goods_price": goods_price, "goods_weight": goods_weight, "upd_time": upd_time})
        goods = goods_base.first()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
    if count != 0:
        data_dict = {"data": goods.to_dict(), "meta": {"code": 200, "msg": "修改商品成功"}}
    else:
        data_dict = {"meta": {"code": 400, "msg": "修改商品失败"}}
    return jsonify(data_dict)


@good.route("/upload", methods=['POST'])
# @verify
def upload():
    # print(request.headers)
    data = request.files
    print(data)
    file = None
    res = {}
    if data:
        file = data.get("file")
        try:
            res = FDFS.upload_by_buffer(file.read())
            print(res)
            if res.get("Status") == 'Upload successed.':
                res = {"code": 200, "msg": "上传成功",
                       "meta": {"pic": res.get("Remote file_id").decode("utf-8")}}
            else:
                res = {"code": 400, "msg": "上传失败"}
        except Exception as e:
            current_app.logger.error(e)
            res = {"code": 400, "msg": "上传失败"}
    return jsonify(res)


@good.route("add", methods=["POST"])
@verify
def add_goods():
    data = json.loads(request.get_data()) if request.get_data() else {}
    res = {}
    if data:
        goods_name = data.get("goods_name")
        goods_number = data.get("goods_number")
        goods_price = data.get("goods_price")
        goods_weight = data.get("goods_weight")
        goods_introduce = data.get("goods_introduce")
        goods_pics = data.get("pics")
        attrs = data.get("attrs")
        cat_id = data.get("cat_id")
        try:
            goods = Goods()
            goods.is_del = '0'
            goods.goods_name = goods_name
            goods.goods_weight = goods_weight
            goods.goods_introduce = goods_introduce
            goods.goods_price = decimal.Decimal(goods_price)
            goods.goods_number = goods_number
            goods.add_time = time.time()
            goods.upd_time = time.time()
            goods.goods_big_logo = goods_pics[0]
            goods.goods_small_logo = goods_pics[1]
            goods.cat_id = cat_id[2]
            goods.cat_one_id = cat_id[0]
            goods.cat_two_id = cat_id[1]
            goods.cat_three_id = cat_id[2]
            db.session.add(goods)
            db.session.flush()
            # db.session.commit()
            for attr in attrs:
                for item in attr:
                    goodsAttr = GoodsAttr()
                    goodsAttr.attr_id = item.get("attr_id")
                    goodsAttr.attr_value = item.get("attr_vals")
                    goodsAttr.goods_id = goods.goods_id
                    goodsAttr.add_price = decimal.Decimal("0")
                    db.session.add(goodsAttr)
                    # db.session.commit()

            if len(goods_pics) >3:
                count = 0
                for pic in goods_pics:
                    count += 1
                    if count >=3:
                        goodsPics = GoodsPics()
                        goodsPics.goods_id = goods.goods_id
                        goodsPics.pics_big = goods_pics[0]
                        goodsPics.pics_mid = goods_pics[1]
                        goodsPics.pics_sma = goods_pics[count]
                        db.session.add(goodsPics)
            else:
                goodsPics = GoodsPics()
                goodsPics.goods_id = goods.goods_id
                goodsPics.pics_big = goods_pics[0]
                goodsPics.pics_mid = goods_pics[1]
                goodsPics.pics_sma = goods_pics[2]
                db.session.add(goodsPics)
            db.session.commit()
            res = {"code": 200, "msg": "添加商品成功"}
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            res = {"code": 400, "msg": "添加商品失败"}
    return jsonify(res)
